﻿
using System ;
using System.Collections.Generic ;

using MskEdit.Sdk ;


namespace MskEdit.Dxf.Model
{

    public class DxfEntities : DxfStructBase
    {
        private Lazy<DxfEntity[]> entities_ ;
        
        
        internal static DxfEntity[] getEntities( string [] allLines, SdkSubrange subrange ) {
        
            List<DxfEntity> dxfEntities = new List<DxfEntity>() ;
            
            DxfEntity dxfEntitiy = null ;
            int lineNo = subrange.Begin ;
            
            do {
                do {
                
                    dxfEntitiy = DxfAttdefEntity.TryFrom( allLines, ref lineNo, null ) ;
                    if ( dxfEntitiy != null )
                        break ;
                                     
                    dxfEntitiy = DxfAttribEntity.TryFrom( allLines, ref lineNo, null ) ;
                    if ( dxfEntitiy != null )
                        break ;                        
                                     
                    dxfEntitiy = DxfTextEntity.TryFrom( allLines, ref lineNo, null ) ;
                    if ( dxfEntitiy != null )
                        break ;                        
                      
                    dxfEntitiy = DxfEntity.TryFrom( allLines, ref lineNo, null ) ;
                    if ( dxfEntitiy == null )
                        break ; 
                        
                } while ( false ) ;
                
                if ( dxfEntitiy != null ) 
                    dxfEntities.Add( dxfEntitiy ) ;
                    
            } while ( dxfEntitiy != null ) ;
            
            return dxfEntities.ToArray() ;
        }


        public DxfEntities( string[] allLines, SdkSubrange subrange ) : base ( allLines, subrange ) {
        
            SdkSubrange innerSubrange = new SdkSubrange( subrange.Begin + 2, subrange.Length - 2 ) ;
            entities_ = new Lazy<DxfEntity[]>( () => { return getEntities( allLines, innerSubrange ) ; } ) ;
            
        }
                
        
        public string TryGetAttribText( string attribTag, string fallbackValue ) {
        
            string text = null ;
            
            foreach ( DxfEntity dxfEntity in entities_.Value ) {
                
                DxfAttribEntity dxfAttribEntity = dxfEntity as DxfAttribEntity ;
                if ( dxfAttribEntity == null )
                    continue ;
                    
                if ( dxfAttribEntity.Tag != attribTag )
                    continue ;
                    
                text = dxfAttribEntity.Default ;
            }
            
            if ( text == null )
                return fallbackValue ;
                
            return text ;
        }

        
        public DxfEntity[] Entities {
            get { return entities_.Value ; }
        }
    }
}
